package com.xiaochong.tir.apiservice.scheduled;

import com.xc.logclient.utils.LogTrace;
import com.xiaochong.tir.apiservice.config.ExecutorConfig;
import com.xiaochong.tir.apiservice.thread.KLineQuantizationApiThread;
import com.xiaochong.tir.common.data.mapper.ExchangeInfoMapper;
import com.xiaochong.tir.common.data.po.ExchangeInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;

/**
 * @Description: k线行情组装数据
 * @Author: org
 * @CreateDate: 2018/7/5 15:17
 */
@Component
public class KLineQuantizationScheduled {

    @Autowired
    private ExchangeInfoMapper exchangeInfoMapper;
    private static final int COUNT = 1;
   private Semaphore semaphore = new Semaphore(COUNT, true);

    @Async(ExecutorConfig.SCHEDULER_EXECUTOR_POOL)
   // @Scheduled(fixedRate = 1000*16)
    @Scheduled(cron="0/16 * * * * ?")
    public void calculateNewHighAndLow() throws Exception {

    	try{
    		if(semaphore.tryAcquire(COUNT)){
                LogTrace.beginTrace();
                long start = System.currentTimeMillis();
                LogTrace.info("thread-KLine组装k线行情列表数据","start",String.valueOf(start));
                //查询所有交易所，循环调取akka
                ExchangeInfo exchangeInfo=new ExchangeInfo();
                exchangeInfo.setEnableFlag( true );
                exchangeInfo.setDeleteFlag( false );
                exchangeInfo.setKlineStatus( true );
                List<ExchangeInfo> infoList=exchangeInfoMapper.selectByEntityList( exchangeInfo );
                if(infoList != null && infoList.size() >0){
                    CountDownLatch countDownLatch = new CountDownLatch( infoList.size()+1);
                    for(ExchangeInfo exchange : infoList){
                        Thread thread = new Thread(new KLineQuantizationApiThread(exchange.getId(),2,countDownLatch));
                        thread.setName("KLineQuantizationApiThread-"+exchange.getId());
                        thread.start();
                    }
                    //精选数据组装
                    Thread thread = new Thread(new KLineQuantizationApiThread(null,1,countDownLatch));
                    thread.setName("KLineQuantizationApiThread-"+0);
                    thread.start();
                    countDownLatch.await();
                }
                LogTrace.info("thread-KLine组装k线行情列表数据","end",String.valueOf(System.currentTimeMillis()-start));
            }
    	}catch(Throwable t){
    		t.printStackTrace();
    	}finally{
    		semaphore.release(COUNT);
    	}
        
    }


}
